package com.lx.user.web;

import com.lx.bean.Result;
import com.lx.bilibili.entity.Video;
import com.lx.user.TencentConfig;
import com.lx.user.dao.UploadMapper;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.http.HttpMethodName;
import com.qcloud.cos.model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("upload")
public class UploadController {

    @Autowired
    UploadMapper uploadMapper;

    @Autowired
    TencentConfig tencentConfig;


    @RequestMapping("videoUpload")
    public int videoUpload(@RequestBody Video video) {
        video.setTime(new Timestamp(System.currentTimeMillis()));
        return uploadMapper.insert(video);
    }

    @RequestMapping("test")
    public int test() {
        // 指定要上传的文件
        File localFile = new File("D:/upload/fd2dbe7449ce4e7a82cd82f7921c6fb2.mp4");
// 指定文件将要存放的存储桶
        String bucketName = "bilibili-video-1355540551";
// 指定文件上传到 COS 上的路径，即对象键。例如对象键为 folder/picture.jpg，则表示将文件 picture.jpg 上传到 folder 路径下
        String key = "folder/fd2dbe7449ce4e7a82cd82f7921c6fb2.mp4";
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);
        PutObjectResult putObjectResult = tencentConfig.cosClientnew(tencentConfig.getSecretId(), tencentConfig.getSecretKey(), tencentConfig.getRegionName()).putObject(putObjectRequest);
        System.out.println("putObjectResult = " + putObjectResult);
        ListObjectsRequest listObjectsRequest = new ListObjectsRequest();
// 设置 bucket 名称
        listObjectsRequest.setBucketName(bucketName);
// prefix 表示列出的 object 的 key 以 prefix 开始
//        listObjectsRequest.setPrefix("/");
// deliter 表示分隔符, 设置为/表示列出当前目录下的 object, 设置为空表示列出所有的 object
        listObjectsRequest.setDelimiter("");
// 设置最大遍历出多少个对象, 一次 listobject 最大支持1000
        listObjectsRequest.setMaxKeys(1000);
        ObjectListing objectListing = null;
        do {
            try {
                objectListing = tencentConfig.cosClientnew(tencentConfig.getSecretId(), tencentConfig.getSecretKey(), tencentConfig.getRegionName()).listObjects(listObjectsRequest);
            } catch (CosServiceException e) {
                e.printStackTrace();
                return 0;
            } catch (CosClientException e) {
                e.printStackTrace();
                return 0;
            }
            // common prefix 表示被 delimiter 截断的路径, 如 delimter 设置为/, common prefix 则表示所有子目录的路径
            List<String> commonPrefixs = objectListing.getCommonPrefixes();

            // object summary 表示所有列出的 object 列表
            List<COSObjectSummary> cosObjectSummaries = objectListing.getObjectSummaries();
            for (COSObjectSummary cosObjectSummary : cosObjectSummaries) {
                // 文件的路径 key
                String key1 = cosObjectSummary.getKey();
                // 文件的 etag
                //etag是由对象内容的哈希值生成的文件内容标识符
                String etag = cosObjectSummary.getETag();
                // 文件的长度
                long fileSize = cosObjectSummary.getSize();
                // 文件的存储类型
                String storageClasses = cosObjectSummary.getStorageClass();
                // 设置URL过期时间
                Date expirationDate = new Date(System.currentTimeMillis() + 60 * 60 * 1000);

                // 生成请求
                GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(bucketName, key1, HttpMethodName.GET);
                req.setExpiration(expirationDate);

                // 生成URL
                URL url = tencentConfig.cosClientnew(tencentConfig.getSecretId(), tencentConfig.getSecretKey(), tencentConfig.getRegionName()).generatePresignedUrl(req);
                String urlString = url.toString();
                System.out.println(urlString);
            }
//            //实现分页查询存储桶的对象列表，因为设置了一次请求最多返回1000个对象信息，所以如果超出1k个就进行分页
//            String nextMarker = objectListing.getNextMarker();
//            //setMarker用来设置下一页的起始位置
//            listObjectsRequest.setMarker(nextMarker);

        } while (objectListing.isTruncated());
        return 1;
    }


    @RequestMapping("uploadVideoToCos")
    public Result uploadVideoToCos(@RequestParam("file") MultipartFile  multipartFiles) throws IOException {

        // 初始化腾讯云 COS 客户端
        COSClient cosClient = tencentConfig.cosClientnew(tencentConfig.getSecretId(),tencentConfig.getSecretKey(),tencentConfig.getRegionName());
        List<String> keyList = new ArrayList<>();
            // 配置上传图片的元数据
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(multipartFiles.getSize());

            String oldFileName = multipartFiles.getOriginalFilename();
            String fileType = "mp4";//文件类型
            int dotIndex = oldFileName.lastIndexOf('.');
            if (dotIndex > 0 && dotIndex < oldFileName.length() - 1) {
                fileType = oldFileName.substring(dotIndex + 1).toLowerCase();
            }
            // 配置腾讯云 COS 存储路径
            // 生成上传到服务器的文件路径和随机文件名
            String randomUUID = UUID.randomUUID().toString();
            // 文件夹
            String folder = "upVideo/";
            String key = folder +  randomUUID.replace("-", "") + "." + fileType;

            // 使用腾讯云 COS SDK 上传图片
            PutObjectRequest putObjectRequest = new PutObjectRequest(tencentConfig.getBucketName(), key, multipartFiles.getInputStream(), objectMetadata);
            cosClient.putObject(putObjectRequest);

            String videoUrl = tencentConfig.getCosPath() +"/"+ key;
            keyList.add(videoUrl);
            System.out.println(videoUrl);

            return new Result(1, "上传成功，请等待审核", videoUrl);

    }

}
